#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#define ElementType int
void sys_err(char* str){
    perror(str);
}
typedef struct SlistNode{
    ElementType date;
    struct SlistNode* next;
}SNode;

int NumSlist(SNode* phead){
    int count = 0;
    if (phead == NULL)//空链表
        return count;
    else//非空，>= 1
        count = 1;
    while (phead->next != NULL){//形式参数头指针，遍历链表
        count++;
        phead = phead->next;
    }
    return count;
}

SNode* CreatNewNode(ElementType x){
    SNode* ptmp = (SNode* )malloc(sizeof(SNode ) );
    ptmp->date = x;
    ptmp->next = NULL;
    return ptmp;
}

void PushBack(SNode** pphead, ElementType x){//尾插
    SNode* cur = *pphead;//遍历指针cur，初始化时指向头节点
    if (*pphead == NULL )
        *pphead = CreatNewNode(x);
    else{
        while (cur->next != NULL){//找尾
            cur = cur->next;
        }
        cur->next = CreatNewNode(x); 
    }
}

void ShowList(SNode* phead){
    SNode* cur = phead;
    if (cur == NULL)
        printf("空链表");
    else{
        while (cur->next != NULL )//不是尾节点，打印；尾节点，结束打印
        {
            printf("%d ",cur->date);
            cur = cur->next;
        }   printf("%d\n",cur->date);//打印尾节点内部的内容,顺便还行
    }
}

void DelNode(SNode* phead, int n){//删除指定节点
    SNode* cur = phead;
    int num = NumSlist(cur),count = 0;//count为指针移动次数
    SNode* tmp = NULL;//临时指针
    if (n < 0 || n > num){
        puts("删除的节点不再链表内，或者删除的节点违法");
        return ;
    }
    while (count < n-2){//确定n-1号节点,从第1个节点跳转到第n-1号节点，需要跳转n-2次
        cur = cur->next;
        count++;
    }
    tmp = cur->next;//找到第倒数第n个
    cur->next = tmp->next;
    free(tmp);
}

ElementType SeeSNode(SNode* phead, int n){//查看指定位置的节点数据
    int num = NumSlist(phead),count;
    SNode* cur = phead;
    if (n < 0 || n > num){
        puts("查看的节点不再链表内，或者查看的节点违法");
        return (ElementType)-1;
    }
   while (count < n-1){
        cur = cur->next;
        count++;
   } 
   return cur->date;
}

void ModSNode(SNode* phead, int n,ElementType x){
    int num = NumSlist(phead),count = 0;
    SNode* cur = phead;
    if (n < 0 || n > num)
        puts("Node isn't exits int the current list,or the Node is illegal");
    else{ 
        while (count < n-1){
            cur = cur->next;
            count++;
        }
        cur->date = x;
    }
}

int main(int argc,char* argv[]){
    SNode* phead = NULL;
    for (int i = 0; i < 5; i++){
        PushBack(&phead, i);
    }
    ShowList(phead);

    DelNode(phead, 6);

    ShowList(phead);
    printf("%d\n",SeeSNode(phead, 3));

    ModSNode(phead, 3, 10);
    ShowList(phead);
}
